package order

import (
	"context"
	"strconv"

	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/svc"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/utils/dberrorhandler"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/types/pancakebot"
	"github.com/agui-coder/simple-admin-pay-rpc/types/pay"

	"github.com/zeromicro/go-zero/core/errorx"
	"github.com/zeromicro/go-zero/core/logx"
)

type RefundPancakebotOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRefundPancakebotOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RefundPancakebotOrderLogic {
	return &RefundPancakebotOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RefundPancakebotOrderLogic) RefundPancakebotOrder(in *pancakebot.RefundPancakebotOrderReq) (*pancakebot.BaseResp, error) {
	// 1. 查询订单
	order, err := l.svcCtx.DB.PancakebotOrder.Get(l.ctx, in.Id)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, "pancakebot order not found")
	}

	// 2. 验证订单是否已支付
	if !order.PayStatus {
		logx.Errorf("[RefundPancakebotOrder][order(%d) 订单未支付，无法退款]", in.Id)
		return nil, errorx.NewInvalidArgumentError("PANCAKEBOT_ORDER_NOT_PAID")
	}

	// 3. 验证订单是否已退款
	if order.PayRefundID != 0 {
		logx.Errorf("[RefundPancakebotOrder][order(%d) 订单已退款，请勿重复操作，退款ID: %d]", in.Id, order.PayRefundID)
		return nil, errorx.NewInvalidArgumentError("PANCAKEBOT_ORDER_ALREADY_REFUNDED")
	}

	// 4. 构建退款请求参数
	merchantRefundId := strconv.FormatUint(order.ID, 10) + "-refund"
	refundPrice := int32(order.Price * 100)

	// 5. 调用支付服务创建退款订单
	refundResp, err := l.svcCtx.PayRpc.CreateRefund(l.ctx, &pay.RefundCreateReq{
		UserIp:           in.UserIp,
		MerchantOrderId:  strconv.FormatUint(in.Id, 10),
		MerchantRefundId: merchantRefundId,
		Reason:           "用户申请退款",
		Price:            refundPrice,
	})

	if err != nil {
		logx.Errorf("[RefundPancakebotOrder][order(%d) 创建退款订单失败: %v]", in.Id, err)
		return nil, err
	}

	// 6. 更新订单退款信息
	err = l.svcCtx.DB.PancakebotOrder.UpdateOneID(in.Id).
		SetPayRefundID(refundResp.Id).
		SetRefundPrice(refundPrice).
		Exec(l.ctx)

	if err != nil {
		logx.Errorf("[RefundPancakebotOrder][order(%d) 更新订单退款信息失败: %v]", in.Id, err)
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, "update pancakebot order refund info error")
	}

	logx.Infof("[RefundPancakebotOrder][order(%d) 退款订单创建成功，退款ID: %d, 退款金额: %d]",
		in.Id, refundResp.Id, refundPrice)

	return &pancakebot.BaseResp{Msg: refundResp.Msg}, nil
}
